package net.bblot.lottery.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImageUtils {

    /**
     * 图片压缩后的大边长度
     */
    public final static int IMAGE_WIDTH_MAX = 1280;
    /**
     * 图片压缩后的小边长度
     */
    public final static int IMAGE_HEIGHT_MAX = 960;
    public final static String SDCARD_MNT = "/mnt/sdcard";
    public final static String SDCARD = "/sdcard";

    public static String getAbsolutePathFromUri(Activity context, Uri mUri) {
        String filePath = null;
        filePath = ImageUtils.getAbsolutePathFromNoStandardUri(mUri);
        // 如果是标准Uri
        if (filePath == null || filePath.length() > 2) {
            filePath = ImageUtils.getAbsoluteImagePath(context, mUri);
        }

        return filePath;
    }

    /**
     * 通过uri获取文件的绝对路径
     *
     * @param uri
     * @return
     */
    public static String getAbsoluteImagePath(Activity context, Uri uri) {
        String imagePath = "";
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.managedQuery(uri, proj, // Which columns to
                // return
                null, // WHERE clause; which rows to return (all rows)
                null, // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)

        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if (cursor.getCount() > 0 && cursor.moveToFirst()) {
                imagePath = cursor.getString(column_index);
            }
        }

        return imagePath;
    }

    /**
     * 判断当前Url是否标准的content://样式，如果不是，则返回绝对路径
     *
     * @param mUri
     * @return
     */
    public static String getAbsolutePathFromNoStandardUri(Uri mUri) {
        String filePath = null;

        String mUriString = mUri.toString();
        mUriString = Uri.decode(mUriString);

        String pre1 = "file://" + SDCARD + File.separator;
        String pre2 = "file://" + SDCARD_MNT + File.separator;

        if (mUriString.startsWith(pre1)) {
            filePath = Environment.getExternalStorageDirectory().getPath() + File.separator
                    + mUriString.substring(pre1.length());
        } else if (mUriString.startsWith(pre2)) {
            filePath = Environment.getExternalStorageDirectory().getPath() + File.separator
                    + mUriString.substring(pre2.length());
        }
        return filePath;
    }

    public static String compressImage(Context context, String filePath, String compressFilePath) {
        if (!TextUtils.isEmpty(filePath)) {
            File file = new File(filePath);
            if (file.length() < 300 * 1024) {
                return filePath;
            }
        }
        if (compressFilePath == null) {
            if (context.getExternalCacheDir() != null) {
                compressFilePath = context.getExternalCacheDir().getAbsolutePath() + File.separator +
                        "tmp_compressFilePath" + File.separator
                        + System.currentTimeMillis() + ".jpg";
            } else {
                compressFilePath = context.getCacheDir().getAbsolutePath() + File.separator +
                        "tmp_compressFilePath" + File.separator
                        + System.currentTimeMillis() + ".jpg";
            }
        }

        {
            // 先计算图片原本大小
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inSampleSize = 1;
            opts.inJustDecodeBounds = true;
            Bitmap cur_bitmap = BitmapFactory.decodeFile(filePath, opts);
            int max = opts.outWidth > opts.outHeight ? opts.outWidth : opts.outHeight;
            double compress_rate0 = (max + 0.0) / IMAGE_WIDTH_MAX;
            double compress_rate1 = (max + 0.0) / IMAGE_HEIGHT_MAX;
            double compress_rate = compress_rate0 < compress_rate1 ? compress_rate0 :
                    compress_rate1;
            int outWidth = (int) (opts.outWidth / compress_rate);
            int outHeight = (int) (opts.outHeight / compress_rate);
            int quality = 90;
            if (max > IMAGE_WIDTH_MAX) {
                opts.inSampleSize = (int) Math.round((max / IMAGE_WIDTH_MAX));
                opts.inJustDecodeBounds = false;
                opts.outWidth = outWidth;
                opts.outHeight = outHeight;
                quality = (int) (100 / compress_rate);
                cur_bitmap = BitmapFactory.decodeFile(filePath, opts);
            } else {
                opts.inJustDecodeBounds = false;
                opts.inSampleSize = (int) Math.round((max / IMAGE_WIDTH_MAX));
                cur_bitmap = BitmapFactory.decodeFile(filePath, opts);
            }

            if (cur_bitmap == null) {
                return filePath;
            } else {
                try {
                    ExifInterface exifInterface = new ExifInterface(filePath);
                    int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                            ExifInterface.ORIENTATION_NORMAL);
                    int degree = 0;
                    switch (orientation) {
                        case ExifInterface.ORIENTATION_ROTATE_90:
                            degree = 90;
                            break;
                        case ExifInterface.ORIENTATION_ROTATE_270:
                            degree = 270;
                            break;
                        case ExifInterface.ORIENTATION_ROTATE_180:
                            degree = 180;
                        default:
                            break;
                    }
                    if (degree != 0) {

                    }
                    cur_bitmap = rotaingImageView(degree, cur_bitmap);

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    Logger.e("ImageUtils", "filePath2=+ IOException");
                    e.printStackTrace();
                }
            }
            try {

                saveImageToSD(context, compressFilePath, cur_bitmap, quality);
                // Logger.e(">>>>>>3333>>>>", "new File(filePath)" + new
                // File(filePath).length() + "compress.getTotalSpace()"
                // + new File(compressFilePath).length());
                return compressFilePath;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return filePath;
            }
        }

    }

    /**
     * @param angle
     * @param bitmap
     * @return Bitmap 返回类型
     * @Title: rotaingImageView
     * @author 谢会超
     * @Description: TODO(旋转图片)
     * @date 创建(修改时间) 2013-12-20 下午6:15:50
     */

    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {

        // 旋转图片 动作

        Matrix matrix = new Matrix();
        matrix.postRotate(angle);

        // 创建新的图片

        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,

                bitmap.getWidth(), bitmap.getHeight(), matrix, true);

        return resizedBitmap;

    }

    /**
     * 写图片文件到SD卡
     *
     * @throws IOException
     */
    public static void saveImageToSD(Context ctx, String filePath, Bitmap bitmap, int quality) throws IOException {
        if (bitmap != null) {

            File file = new File(filePath.substring(0, filePath.lastIndexOf(File.separator)));
            if (!file.exists()) {
                file.mkdirs();
            }
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
            bos.flush();
            bos.close();
            scanPhoto(ctx, filePath);
        }
    }

    /**
     * 让Gallery上能马上看到该图片
     */
    private static void scanPhoto(Context ctx, String filePath) {
        Intent mediaScanIntent = new Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File file = new File(filePath);
        Uri contentUri = Uri.fromFile(file);
        mediaScanIntent.setData(contentUri);
        ctx.sendBroadcast(mediaScanIntent);
    }

    /**
     * 将文件转成base64 字符串
     *
     * @param path 图片文件路径
     * @return *
     * @throws Exception
     */

    public static String encodeBase64File(String path) throws Exception {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos);
        byte[] bytes = baos.toByteArray();
        //base64 encode
        return "data:image/jpg;base64," + Base64.encodeToString(bytes, Base64.NO_WRAP);
    }
}